package top.broncho.anpods.ui.settings

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.Settings
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.tencent.bugly.beta.Beta
import kotlinx.android.synthetic.main.settings_activity.*
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.jetbrains.anko.*
import top.broncho.anpods.ACTION_POPUP
import top.broncho.anpods.AnPodsService
import top.broncho.anpods.BuildConfig
import top.broncho.anpods.R
import top.broncho.anpods.guide.GuideActivity
import top.broncho.anpods.ui.widget.PermissionDialog
import top.broncho.anpods.ui.widget.onOffsetChanged
import top.broncho.anpods.util.MODEL_AIR_PODS_2
import top.broncho.anpods.util.MODEL_AIR_PODS_PRO
import top.broncho.anpods.util.getStr
import top.broncho.anpods.util.onPrefChange
import kotlin.math.abs

class SettingsActivity : AppCompatActivity(), AnkoLogger {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!Settings.canDrawOverlays(this)) {
            startActivity<GuideActivity>()
        }
        setContentView(R.layout.settings_activity)
        startService(Intent(this, AnPodsService::class.java))
        supportFragmentManager
            .beginTransaction()
            .replace(
                R.id.settings,
                SettingsFragment()
            )
            .commit()
        fab.setOnClickListener {
            startService(Intent(this, AnPodsService::class.java).apply { action = ACTION_POPUP })
        }
        appBar.onOffsetChanged().onEach {
            onOffsetChanged(it)
        }.launchIn(lifecycleScope)
        checkAirPodsGen()
        defaultSharedPreferences.onPrefChange().onEach {
            if (it == "key_model") checkAirPodsGen()
        }.launchIn(lifecycleScope)
    }

    private fun checkAirPodsGen() {
        val model = getStr("key_model")
        iv_logo.setAnimation(
            when (model) {
                MODEL_AIR_PODS_PRO -> R.raw.case_empty_pro
                MODEL_AIR_PODS_2 -> R.raw.case_empty_gen_two
                else -> R.raw.case_empty_gen_one
            }
        )
        iv_logo_left.setAnimation(if (model == MODEL_AIR_PODS_PRO) R.raw.case_left_pro else R.raw.case_left)
        iv_logo_right.setAnimation(if (model == MODEL_AIR_PODS_PRO) R.raw.case_right_pro else R.raw.case_right)
        iv_left_pod.setAnimation(if (model == MODEL_AIR_PODS_PRO) R.raw.airpod_left_pro else R.raw.airpod_left)
        iv_right_pod.setAnimation(if (model == MODEL_AIR_PODS_PRO) R.raw.airpod_right_pro else R.raw.airpod_right)
    }

    private fun onOffsetChanged(verticalOffset: Int) {
        when {
            (verticalOffset == 0) -> {
                if (iv_logo.progress == 0f) {
                    iv_logo.playAnimation()
                    iv_logo_left.playAnimation()
                    iv_logo_right.playAnimation()
                    iv_left_pod.playAnimation()
                    iv_right_pod.playAnimation()
                }
            }
            (abs(verticalOffset) >= appBar.totalScrollRange) -> {
                iv_logo.progress = 0f
                iv_logo_left.progress = 0f
                iv_logo_right.progress = 0f
                iv_left_pod.progress = 0f
                iv_right_pod.progress = 0f
            }
        }
    }

    class SettingsFragment : PreferenceFragmentCompat(), AnkoLogger {
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)
            val versionPreference = findPreference<Preference>("key_version")
            versionPreference?.summary =
                getString(
                    R.string.version_summary,
                    BuildConfig.VERSION_NAME
                )
        }

        override fun onPreferenceTreeClick(preference: Preference?): Boolean {
            when (preference?.key) {
                "key_permission" -> {
                    context?.run {
                        PermissionDialog(this).show()
                    }
                }
                "key_share" -> context?.share("给你推荐一款可以查看AirPods电量的App: https://www.pgyer.com/AnPods")
                "key_feedback" -> {
                    context?.email("way.ping.li@gmail.com", "AnPods Feedback", "")
                }
                "key_version" -> Beta.checkAppUpgrade()
                else -> {
                }
            }
            return super.onPreferenceTreeClick(preference)
        }

    }

}